package base.thread_JUC2.chapter05.demo01;

import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

/**
 * 任务：将1万件产品的价格由10元，变更为12元。
 * 每个任务只能更新少于10件产品。（java会自动将一个任务拆分成多个任务）
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        // 1w件产品
        ProductListGenerator generator = new ProductListGenerator();
        List<Product> products = generator.generate(10000);

        // 创建任务
        Task task = new Task(products, 0, products.size(), 0.2);

        // 创建 ForkJoinPool 池,默认根据CPU核心数来生成线程池数大小
        ForkJoinPool pool = new ForkJoinPool();
        pool.execute(task);

        // 监控线程池中执行情况
        do{
            System.out.printf("Main: Thread Count: %d\n",pool.getActiveThreadCount());
            System.out.printf("Main: Thread Steal: %d\n",pool.getStealCount());
            System.out.printf("Main: Paralelism: %d\n",pool.getParallelism());

            TimeUnit.MILLISECONDS.sleep(5);
        }while (!task.isDone());

        // 停止执行器
        pool.shutdown();

        // 检查任务是否正常完成
        if (task.isCompletedNormally()) {
            System.out.printf("Main: The process has completed normally.\n");
        }

        // 校验：预期结果12。写出价格不是12的产品
        for (Product product : products) {
            if (product.getPrice()!=12) {
                System.out.printf("异常修改产品： %s: %f\n",product.getName(),product.getPrice());
            }
        }
        System.out.println("Main: End of the program.\n");
    }
}
